/**
 * 订单管理
 */
var pageCurr;
var form;
var openId;
$(function() {
    layui.use('table', function(){
        var table = layui.table;
        form = layui.form;

        tableIns=table.render({
            elem: '#userInfoList',
            url:'/userInfo/getUserInfoList',
            method: 'post', //默认：get请求
            cellMinWidth: 80,
            page: true,
            request: {
                pageName: 'pageNum', //页码的参数名称，默认：pageNum
                limitName: 'pageSize' //每页数据量的参数名，默认：pageSize
            },
            response:{
                statusName: 'code', //数据状态的字段名称，默认：code
                statusCode: 200, //成功的状态码，默认：0
                countName: 'totals', //数据总数的字段名称，默认：count
                dataName: 'list' //数据列表的字段名称，默认：data
            },
            cols: [[
                {type:'numbers'}
                ,{field:'buyerOpenid', title:'用户编号',align:'center'}
                ,{field:'userNickname', title: '用户昵称',align:'center'}
                ,{field:'userSex', title: '性别',align:'center'}
                ,{field:'userProvince', title: '所在省份',align:'center'}
                ,{field:'userCity', title: '所在城市',align:'center'}
                ,{field:'userInfoLabel', title: '账号状态',align:'center'}

                ,{field:'createTime4', title: '创建时间',align:'center'}
                ,{field:'updateTime4', title: '更新时间',align:'center'}
                ,{field:'isWorker',title: '注册师傅',align:'center'}
                ,{title:'操作',align:'center', toolbar:'#optBar'}

            ]],
            done: function(res, curr, count){
                //如果是异步请求数据方式，res即为你接口返回的信息。
                //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                //console.log(res);
                //得到当前页码
                console.log(curr);
                $("[data-field='userSex']").children().each(function(){
                    if($(this).text()=='1'){
                        $(this).text("男")
                    }else if($(this).text()=='2'){
                        $(this).text("女")
                    }
                });
                $("[data-field='userInfoLabel']").children().each(function(){
                    if($(this).text()=='1'){
                        $(this).text("禁止")
                    }else if($(this).text()=='0'){
                        $(this).text("允许")
                    }
                });
                $("[data-field='isWorker']").children().each(function(){
                    if($(this).text()=='1'){
                        $(this).text("否")
                    }else if($(this).text()=='0'){
                        $(this).text("是")
                    }
                });
                //得到数据总量
                //console.log(count);
                pageCurr=curr;
            }
        });

        //监听工具条
        table.on('tool(userInfoTable)', function(obj){
            var data = obj.data;
            openId = data.buyerOpenid;
            if(obj.event === 'see'){
                //查看
                seeUserInfo(data,"查看详情");
            }else if(obj.event === 'recover'){
                //恢复
                recoverUser(data,data.buyerOpenid);
            }else if(obj.event === 'del'){
                //恢复
                delUser(data,data.buyerOpenid);
            }
        });

        /*//监听提交
        form.on('submit(userInfoSubmit)', function(data){
            // TODO 校验
            formSubmit(data);
            return false;
        });*/
    });

    //搜索框
    layui.use(['form','laydate'], function(){
        var form = layui.form ,layer = layui.layer
            ,laydate = layui.laydate;
        ///////
        /*var src='<option value="">请选择...</option>';
         $.ajax({
             url:'/order/getOrderStatus',
             dataType:'json',
             async: true,
             success:function(data){
                 $.each(data,function(index,item){
                     if(!orderStatus){
                         var option = new Option(item.name,item.orderStatus);
                     }else {
                         var option = new Option(item.name,item.orderStatus);
                         // // 如果是之前的parentId则设置选中
                         if(item.orderStatus == orderStatus) {
                             option.setAttribute("selected",'true');
                         }
                     }
                     $('#orderStatus').append(option);//往下拉菜单里添加元素
                     form.render('select'); //这个很重要
                 })
             }
         });*/

        ////////
        //TODO 数据校验
        //监听搜索框
        form.on('submit(searchSubmit)', function(data){
            //重新加载table
            load(data);
            return false;
        });
    });
});


function seeUserInfo(data,title) {
    //openId = data.buyerOpenid;
    if(data==null || data==""){
        $("#buyerOpenid0").val("");
    }else{
        $("#buyerOpenid0").val(data.buyerOpenid);
        $("#userNickname").val(data.userNickname);
        if(data.userSex==1){
            $("#userSex0").val("男");
        }else {
            $("#userSex0").val("女");
        }
       // $("#userSex0").val(data.userSex);
        $("#userProvince0").val(data.userProvince);
        $("#userCity0").val(data.userCity);
        $("#userPhone").val(data.userPhone);
        $("#createTime4").val(data.createTime4);
        $("#updateTime4").val(data.updateTime4);

        //////////////////////////////////////
        layui.use('table', function(){
            var table = layui.table;
            form = layui.form;

            tableIns0=table.render({
                elem: '#userAddressList',
                url:'/addressInfo/getAddressInfoList',
                method: 'post', //默认：get请求
                cellMinWidth: 80,
                page: true,
                where: {
                    buyerOpenid: openId   //data.buyerOpenid
                }, //接口的其它参数
                request: {
                    pageName: 'pageNum', //页码的参数名称，默认：pageNum
                    limitName: 'pageSize' //每页数据量的参数名，默认：pageSize

                },
                response:{
                    statusName: 'code', //数据状态的字段名称，默认：code
                    statusCode: 200, //成功的状态码，默认：0
                    countName: 'totals', //数据总数的字段名称，默认：count
                    dataName: 'list' //数据列表的字段名称，默认：data
                },
                cols: [[
                    {type:'numbers'}
                    ,{field:'addressUserName', title:'联系人',align:'center'}
                    ,{field:'addressBuyerPhone', title: '电话',align:'center'}
                    ,{field:'addressArea', title: '所在地区',align:'center'}
                    ,{field:'addressDetail', title: '详细地址',align:'center'}
                    ,{field:'createTime3', title: '创建时间',align:'center'}
                    ,{field:'updateTime3', title: '更新时间',align:'center'}
                    ,{field:'userAddressinfoLabel', title: '地址是否有效',align:'center'}

                ]],
                done: function(res, curr, count){
                    //如果是异步请求数据方式，res即为你接口返回的信息。
                    //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                    //console.log(res);
                    //得到当前页码
                    console.log(curr);
                    $("[data-field='userAddressinfoLabel']").children().each(function(){
                        if($(this).text()=='0'){
                            $(this).text("有效")
                        }else if($(this).text()=='1'){
                            $(this).text("无效")
                        }
                    });
                    //得到数据总量
                    //console.log(count);
                    pageCurr=curr;
                }
            });

            //监听工具条
            table.on('tool(userAddressTable)', function(obj){
                var data = obj.data;

            });
            //////////师傅信息
            tableIns1=table.render({
                elem: '#workerInfo',
                url:'/worker/getWorkers',
                method: 'post', //默认：get请求
                cellMinWidth: 80,
                page: true,
                where: {
                    buyerOpenid: openId  //data.buyerOpenid
                }, //接口的其它参数
                request: {
                    pageName: 'pageNum', //页码的参数名称，默认：pageNum
                    limitName: 'pageSize' //每页数据量的参数名，默认：pageSize

                },
                response:{
                    statusName: 'code', //数据状态的字段名称，默认：code
                    statusCode: 200, //成功的状态码，默认：0
                    countName: 'totals', //数据总数的字段名称，默认：count
                    dataName: 'list' //数据列表的字段名称，默认：data
                },
                cols: [[
                    {type:'numbers'}
                    ,{field:'id', title:'编号',align:'center',width : 60}
                    //,{field:'openId', title:'用户编号',align:'center',width : 60}
                    ,{field:'name', title: '姓名',align:'center',width : 80}
                    ,{field:'phone', title: '电话号码',align:'center',width : 150}
                    //,{field:'picture', title: '照片',align:'center'}
                    , {
                        field: 'picture',
                        title: '照片',
                        //width: 100,
                        align: 'center',
                        templet: function(res) {
                            //return  "<img src='"+datum.formatUrl(d.url)+"' style='height:50px;'";
                            //////
                            ///////图片展示
                            var pictureUrl=res.picture;
                            var picture=pictureUrl.split("/");
                            //$('#demo1').attr('src', "http://localhost:8080/"+picture[picture.length-1]);
                            //////
                            var url =null;
                            if(res.picture!=null){
                                url = "http://localhost:8080/"+picture[picture.length-1];
                            }
                            return '<a href="' + url + '" target="_blank " title="点击查看">' +
                                '<img src="' + url + '" style="height:30px;" />' +
                                '</a>';
                        }
                    }
                    //,{field:'phone', title: '电话号码',align:'center'}
                    ,{field:'score', title: '得分',align:'center',width : 80}
                    ,{field:'createTime10', title: '创建时间',align:'center'}
                    ,{field:'updateTime10', title: '更新时间',align:'center'}
                    ,{field:'status', title: '有效性',align:'center'}
                    ,{field:'isAllowed', title: '禁用',align:'center',width : 60}
                    ,{title:'操作',align:'center', toolbar:'#optBar0',width : 110}

                ]],
                done: function(res, curr, count){
                    //如果是异步请求数据方式，res即为你接口返回的信息。
                    //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                    //console.log(res);
                    //得到当前页码
                    console.log(curr);
                    $("[data-field='status']").children().each(function(){
                        if($(this).text()=='0'){
                            $(this).text("有效")
                        }else if($(this).text()=='1'){
                            $(this).text("无效")
                        }
                    });
                    $("[data-field='isAllowed']").children().each(function(){
                        if($(this).text()=='0'){
                            $(this).text("否")
                        }else if($(this).text()=='1'){
                            $(this).text("是")
                        }
                    });
                    //得到数据总量
                    //console.log(count);
                    pageCurr=curr;
                }
            });

            //监听工具条
            table.on('tool(workerInfoTable)', function(obj){
                var data = obj.data;
                //openId=data.openId;
                if(obj.event === 'del0'){
                    //删除
                    delWorker(data,data.id);
                } else if(obj.event === 'edit0'){
                    //编辑
                    editWorker(data);
                }else if(obj.event === 'recover0'){
                    //恢复
                    recoverWorker(data,data.id);
                }

            });





            //////////师傅信息

            //监听提交
            form.on('submit(workerSubmit)', function(data){
                // TODO 校验
                formSubmit(data);
                return false;
            });
        });


    }
    var pageNum = $(".layui-laypage-skip").find("input").val();
    $("#pageNum").val(pageNum);

    layer.open({
        type:1,
        title: title,
        fixed:false,
        resize :false,
        shadeClose: true,
        area: ['1200px', '750px'],
        content:$('#getUserInfo'),
        end:function(){
            cleanUserInfo();
        }
    });
}


function load(obj){
    //重新加载table
    tableIns.reload({
        where: obj.field
        , page: {
            curr: pageCurr //从当前页码开始
        }
    });


}
function load1(obj){
    //重新加载table
    tableIns1.reload({
        //where: obj.field
        where:{
            buyerOpenid:openId
        }
        , page: {
            curr: pageCurr //从当前页码开始
        }
    });
}

//提交表单
function formSubmit(obj){


    $.ajax({
        type: "post",
        data: $("#workerForm").serialize(),
        url: "/worker/setWorker",
        success: function (data) {
            if (data.code == 1) {
                layer.alert(data.msg,function(index){
                    layer.close(index);
                    layer.close(index-1);
                    load1(obj);
                });
            } else {
                layer.alert(data.msg);
            }
        },
        error: function (data) {
            layer.alert("操作请求错误，请您稍后再试",function(index){
                layer.close(index);
                load1(obj);
            });
        }
    });
}


//打开编辑框
function editWorker(data,title){

    if(data == null){
        $("#id").val("");
    }else{
        //回显数据
        $("#id").val(data.id);
        $("#score").val(data.score);


    }

    var pageNum = $(".layui-laypage-skip").find("input").val();
    $("#pageNum").val(pageNum);

    layer.open({
        type:1,
        title: title,
        fixed:false,
        resize :false,
        shadeClose: true,
        area: ['400px','400px'],
        content:$('#setWorker'),
        end:function(){
            cleanWorker();
        }
    });
}
function cleanWorker(){

}


//删除
function delWorker(obj,id) {
    if(null!=id){
        layer.confirm('您确定要封闭该账号吗？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/worker/updateWorkerIsAllowed",{"id":id,"isAllowed":1},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(index){

                        layer.close(index);
                        load1(obj);
                    });
                } else {

                    layer.alert(data.msg);

                }
            });
        }, function(){
            layer.close();
        });
    }
}
//恢复
function recoverWorker(obj,id) {
    if(null!=id){
        layer.confirm('您确定要恢复该账号吗？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/worker/updateWorkerIsAllowed",{"id":id,"isAllowed":0},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(index){
                        layer.close(index);
                        load1(obj);
                    });
                } else {
                    layer.alert(data.msg);
                }
            });
        }, function(){
            layer.close();
        });
    }
}




//删除
function delUser(obj,buyerOpenid) {
    if(null!=buyerOpenid){
        layer.confirm('您确定要封闭该账号吗？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/userInfo/updateUserLabel",{"buyerOpenid":buyerOpenid,"userInfoLabel":1},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(index){

                        layer.close(index);
                        load(obj);
                    });
                } else {

                    layer.alert(data.msg);

                }
            });
        }, function(){
            layer.close();
        });
    }
}
//恢复
function recoverUser(obj,buyerOpenid) {
    if(null!=buyerOpenid){
        layer.confirm('您确定要恢复该账号吗？', {
            btn: ['确认','返回'] //按钮
        }, function(){
            $.post("/userInfo/updateUserLabel",{"buyerOpenid":buyerOpenid,"userInfoLabel":0},function(data){
                if (data.code == 1) {
                    layer.alert(data.msg,function(index){
                        layer.close(index);
                        load(obj);
                    });
                } else {
                    layer.alert(data.msg);
                }
            });
        }, function(){
            layer.close();
        });
    }
}

function cleanUserInfo(){



}
